<?php
declare (strict_types = 1);

namespace app\middleware;

use app\service\JwtAuth;

class AuthCheck
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        //
        $token = (string) $request->header('Authorization');
        if(empty($token)){
            return error('token不能为空，请重新登录', [], 401);
        }
        $token = str_replace('Bearer ','',$token);
        $ret = JwtAuth::checkToken($token);
        if($ret['status'] != true){
            return error($ret['msg'], [], $ret['code']);
        }

        $tokenParseInfo = $ret['data'] ?? [];
        $authInfo = (array) $tokenParseInfo['data'] ?? null;
        
        $request->authInfo = $authInfo;
        if(!is_null($authInfo)){
            $request->create_by = $authInfo['user_id'];
            $request->user_type = $authInfo['user_type'];
        }
        return $next($request);
    }
}
